import React from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useUserProfile } from '@/hooks/useUserProfile'; //用户登录管理逻辑hooks
import LoginModal from '@/components/LoginModal'; //登录弹窗
import LogoutConfirmModal from '@/components/LogoutConfirmModal'; //退出登录确认弹窗
import TokenBalance from '@/components/TokenBalance'; //引入TokenBalance组件
import vipIcon from '@/assets/images/vip.png'; //会员ICON
import LogoutIcon from '@/assets/images/bxs-log-out-circle.png'; //登出ICON

// 图片URL优化函数，添加OSS压缩参数
const optimizeImageUrl = (url: string, width: number = 500): string => {
    if (!url) return '';

    // 如果已经包含了resize参数，直接返回
    if (url.includes('x-oss-process=image/resize')) return url;

    // 如果是网络图片，添加压缩参数
    if (/^https?:\/\//.test(url)) {
        const separator = url.includes('?') ? '&' : '?';
        return `${url}${separator}x-oss-process=image/resize,w_${width}`;
    }

    return url;
};

interface ChatHeaderProps {
    aiPersonData: {
        avatar: string;
        username: string;
    } | null;
    onAvatarClick: () => void;
    onMoreClick: () => void;
    activeTab: string;
    setActiveTab: (tab: string) => void;
    // 新增语音模式相关props
    generateVoice?: boolean;
    setGenerateVoice?: (v: boolean) => void;
}
/**
 * Chat页面移动端专用Header组件
 * 包含返回按钮、AI头像、姓名、更多按钮和登录模块
 */
const ChatHeader: React.FC<ChatHeaderProps> = ({ aiPersonData, onAvatarClick, onMoreClick, activeTab, setActiveTab, generateVoice, setGenerateVoice }) => {
    const { t } = useTranslation(); //语言国际化
    const navigate = useNavigate(); //跳转

    // 使用统一的用户头像管理 hook
    const {
        isLoggedIn,
        userData,
        showLoginModal,
        isRegisterMode,
        showLogoutButton,
        logoutRef,
        avatarBtnRef,
        handleLoginClick,
        handleRegisterClick,
        handleLoginSuccessAndUpdateTab,
        handleLogoutClick,
        withAvatarResize,
        toggleProfileDropdown,
        closeLoginModal,
        navigateToSubscription,
        showLogoutConfirm,
        confirmLogout,
        cancelLogout
    } = useUserProfile();

    // 包装登录成功处理，添加 setActiveTab 参数与Navigation保持一致
    const handleLoginSuccessWithTab = () => {
        handleLoginSuccessAndUpdateTab(setActiveTab);
    };

    return (
        <>
            {/* 移动端Chat页面Header */}
            <header className="h-16 flex items-center justify-between border-b border-b-[rgb(51,51,57)] text-xl fixed top-0 px-4 left-0 right-0 z-30 bg-[rgb(19,19,19)]">
                {/* 左侧：返回按钮 */}
                <button
                    onClick={() => {
                        // 标记从chat页面返回到home页面
                        sessionStorage.setItem('returnFromChat', 'true');
                        navigate('/');
                    }}
                    className="flex items-center text-white hover:text-pink-500 transition-colors mr-3"
                >
                    <i className="fas fa-arrow-left text-lg"></i>
                </button>

                {/* AI角色信息区域 */}
                <div className="flex items-center flex-1 min-w-0">
                    {/* AI头像 */}
                    <button
                        onClick={onAvatarClick}
                        className="w-10 h-10 rounded-full overflow-hidden border-2 border-pink-500 flex-shrink-0 mr-3"
                    >
                        {aiPersonData?.avatar ? (
                            <img
                                src={optimizeImageUrl(aiPersonData.avatar, 500)}
                                alt="AI Avatar"
                                className="w-full h-full object-cover object-top"
                            />
                        ) : (
                            <div className="w-full h-full bg-gray-600 flex items-center justify-center">
                                <i className="fas fa-robot text-gray-400 text-lg"></i>
                            </div>
                        )}
                    </button>

                    {/* AI姓名 */}
                    <h1 className="text-lg font-medium text-white truncate flex mr-3">
                        {aiPersonData?.username || 'AI Companion'}
                    </h1>



                </div>

                {/* 右侧按钮区域 */}
                <div className="flex items-center space-x-2">

                    {/* 更多按钮 */}
                    <button
                        onClick={onMoreClick}
                        className="p-2 text-white hover:text-pink-500 transition-colors"
                    >
                        <i className="fas fa-ellipsis-h text-lg"></i>
                    </button>
                    {/* 余额展示区域 - 只在登录且有用户数据时显示 */}
                    {isLoggedIn && userData && (
                        <TokenBalance userData={userData} isMobile={true} className="mr-auto" />
                    )}
                    {/* 登录模块 - 与Navigation保持一致 */}
                    {!isLoggedIn && (
                        <>
                            {/* 注册按钮 */}
                            <button
                                className="text-[0.8rem] h-8 px-2 py-1.5 bg-[#E75275] rounded-lg items-center gap-2 inline-flex cursor-pointer"
                                onClick={handleRegisterClick}
                            >
                                <span>{t('common.JoinFree')}</span>
                            </button>
                            {/* 登录按钮 */}
                            <button
                                className="bg-[rgb(19,19,19)] border border-[rgb(221,65,81)] transition-colors text-[rgb(221,65,81)] text-[0.8rem] rounded-[0.5rem] px-2 font-medium focus:outline-none focus:border-[rgb(221,65,81)] hover:border-[rgb(221,65,81)]"
                                onClick={handleLoginClick}
                            >
                                <span>{t('common.login')}</span>
                            </button>
                        </>
                    )}

                    {/* 登录后显示用户头像部分 */}
                    {isLoggedIn && userData && (
                        <div className="relative flex items-center">
                            <div ref={avatarBtnRef} className="relative flex items-center" style={{ height: 32, minWidth: 32 }}>
                                <div
                                    className="w-8 h-8 rounded-full bg-gradient-to-r p-0.5 flex-shrink-0 flex items-center justify-center"
                                    style={{ minWidth: 32, minHeight: 32, cursor: 'pointer' }}
                                    onClick={toggleProfileDropdown}
                                >
                                    <div className="w-full h-full rounded-full overflow-hidden bg-app-dark flex items-center justify-center">
                                        {userData.user_avatar ? (
                                            <img src={withAvatarResize(userData.user_avatar)} alt="avatar" className="w-full h-full object-cover object-top transition-opacity duration-300" />
                                        ) : (
                                            <div className="w-full h-full bg-gray-600 flex items-center justify-center animate-pulse">
                                                <i className="fas fa-user text-gray-400 text-xs"></i>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* 用户头像下拉菜单 */}
                                {userData.login_type === 'google' && showLogoutButton && (
                                    <div
                                        ref={logoutRef}
                                        style={{ backgroundColor: "rgb(24,24,27)", cursor: "pointer" }}
                                        className="absolute top-full right-0 mt-2 bg-[24,24,27] text-white text-[0.85rem] min-w-[140px] px-0 py-2 rounded-lg shadow-lg z-[100]"
                                    >
                                        <div
                                            className="flex items-center px-4 py-2 cursor-pointer hover:bg-[rgba(54,65,83,0.7)] transition-colors"
                                            onClick={navigateToSubscription}
                                        >
                                            <img src={vipIcon} alt="vip" className="w-6 h-6 mr-2" />
                                            <span className="select-none" style={{ color: '#fff' }}>
                                                {t('Subscription')}
                                            </span>
                                        </div>
                                        <div
                                            className="flex items-center px-4 py-2 cursor-pointer hover:bg-[rgba(54,65,83,0.7)] transition-colors"
                                            onClick={handleLogoutClick}
                                        >
                                            <img src={LogoutIcon} alt="logout" className="w-6 h-6 mr-2" />
                                            <span className="select-none" style={{ color: '#fff' }}>
                                                {t('common.logout')}
                                            </span>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    )}
                </div>
            </header>

            {/* 登录弹窗 */}
            <LoginModal
                show={showLoginModal}
                onClose={closeLoginModal}
                onLoginSuccess={handleLoginSuccessWithTab}
                initialRegister={isRegisterMode}
                activeTab={activeTab}
            />
            
            {/* 退出登录确认弹窗 */}
            <LogoutConfirmModal
                show={showLogoutConfirm}
                onClose={cancelLogout}
                onConfirm={confirmLogout}
            />
        </>
    );
};

export default ChatHeader; 